package com.huangliusong.threadcurrency.example.future;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.ExecutionException;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.Future;
import java.util.concurrent.RecursiveTask;

/**
 * @author huangliusong
 * @since 2018/11/23
 * {@link }
 */
@Slf4j
public class ForkJoin extends RecursiveTask<Integer> {
    public static final int thread=2;
    private int start;
    private int end;

    public ForkJoin(int start, int end) {
        this.start=start;
        this.end=end;
    }


    @Override
    protected Integer compute() {
        int sum=0;
        boolean canComputer=(end -start)<=thread;
        if (canComputer){
            for (int i=start;i<=end;i++){
                sum+=i;
            }
        }else {
            //如果任务大于阈值
            int model=(start+end)/2;
            ForkJoin leftTask=new ForkJoin(start,model);
            ForkJoin rightTask=new ForkJoin(model+1,end);
            leftTask.fork();
            rightTask.fork();

            int i1=leftTask.join();
            int i2=rightTask.join();
            sum=i1+i2;
        }
        return sum;
    }


    public static void main(String[] args) throws ExecutionException, InterruptedException {
        ForkJoinPool forkJoinPool=new ForkJoinPool();

        //生成一个计算任务
        ForkJoin forkJoin=new ForkJoin(1,1000);
        //执行一个任务
        Future<Integer> res
                =forkJoinPool.submit(forkJoin);
        System.out.println(res.get());
    }
}
